/*************************************************************************
 * File Name:    Remove_Duplicates_from_Sorted_List_II.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013-11-6 11:03:43
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Remove Duplicates from Sorted List II
 |
 | Given a sorted linked list, delete all nodes that have duplicate numbers,
 | leaving only distinct numbers from the original list.
 |
 | For example,
 | Given 1->2->3->3->4->4->5, return 1->2->5.
 | Given 1->1->1->2->3, return 2->3.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        if (head == NULL) return NULL;
        
        ListNode *ans, *tail;
        ListNode *cur_node = head;
        bool del = false;

        ans = tail = NULL;
        for (ListNode *t = head->next; t != NULL; t = t->next) {
            if (t->val != cur_node->val) {
                if (!del) {
                    if (ans == NULL) {
                        ans = tail = cur_node;
                    } else {
                        tail->next = cur_node;
                        tail = cur_node;
                    }
                }
                cur_node = t;
                del = false;
            } else {
                del = true;
            }
        }
        if (!del) {
            if (tail != NULL) {
                tail->next = cur_node;
                tail = cur_node;
            } else {
                ans = tail = cur_node;
            }
        }
        if (tail != NULL) tail->next = NULL;
        
        return ans;
    }
};

